package com.sinohealth.sca.sender;

import com.sinohealth.sca.listener.PointMessageListener;
import com.sinohealth.sca.model.PointMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Description: 埋点消息发送器
 * @Package: com.sinohealth.sca.sender
 * @Author: chenweifeng
 * @Date: 2024/04/07 上午11:33
 **/
@Component
public class PointMessageSender {

    private final BlockingQueue<PointMessage> messageQueue = new LinkedBlockingQueue<>();

    @Autowired
    private PointMessageListener messageListener;

    @PostConstruct
    public void init() {
        new Thread(this::processMessages).start();
    }

    /**
     * 发送埋点消息
     *
     * @param message
     */
    public void sendMessage(PointMessage message) {
        messageQueue.add(message);
    }

    private void processMessages() {
        while (true) {
            try {
                PointMessage message = messageQueue.take();
                messageListener.handleMessage(message);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}